<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <!-- <el-form-item label="编号记录" prop="num">
        <el-input
          v-model="queryParams.num"
          class="!w-240px"
          clearable
          placeholder="请输入编号记录"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="修改时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button @click="retreat" type="primary" style="float: right">返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column align="center" label="ID" prop="id" />
      <el-table-column align="center" label="库名称" prop="metaName" />
      <el-table-column align="center" label="资源ID" prop="dataId" />
      <el-table-column align="center" label="资源标题" prop="dataName" />
      <el-table-column align="center" label="版本号" prop="num" />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="修改时间"
        prop="createTime"
        width="180"
      />
      <el-table-column :width="300" align="center" label="操作">
        <template #default="scope">
          <el-button
            v-show="isResource"
            v-hasPermi="['resource:meta:update', 'resource:sps:update', 'resource:standard:update']"
            link
            type="primary"
            @click="updateResource(scope.row)"
          >
            查看版本信息
          </el-button>
          <el-button link type="primary" v-show="isResource" @click="impResource(scope.row)">
            资源列表
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <el-dialog
    v-model="showFormDialogFlag"
    :title="formTitle"
    left
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="85%"
    @close="closeForm"
    destroy-on-close
  >
    <v-form-render
      ref="vFormRef"
      :form-json="formJson"
      :form-data="formData"
      :option-data="optionData"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="closeForm">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 表单弹窗：添加/修改 -->
  <RoleForm ref="formRef" @success="getList" />
  <!-- 表单弹窗：菜单权限 -->
  <RoleAssignMenuForm ref="assignMenuFormRef" @success="getList" />
  <!-- 表单弹窗：数据权限 -->
  <RoleDataPermissionForm ref="dataPermissionFormRef" @success="getList" />
</template>
<script lang="ts" setup>
import router from '@/router'
import { dateFormatter } from '@/utils/formatTime'
import * as RoleApi from '@/api/system/role'
import { h, reactive, ref, watch } from 'vue'
import * as metaApi from '@/api/meta'

defineOptions({ name: 'metaVersion' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const route = useRoute()
const id = route.query.id
const metaId = route.query.metaId
const metaName = route.query.metaName
const vFormRef = ref<any>()
const showFormDialogFlag = ref(false)
const formTitle = ref('查看版本记录')
const closeForm = () => {
  //清空表单
  vFormRef.value.resetForm()
  showFormDialogFlag.value = false
}

const formJson = ref({
  widgetList: [],
  formConfig: {}
})

const formData = ref({})
const optionData = ref({})
const updateResource = async (row) => {
  showFormDialogFlag.value = true
  let res = await metaApi.selectMetaDataOne(metaId, id)
  let formDataJson = await vFormRef.value.setFormData(JSON.parse(row.data))
}

const navigationals = ref([])
const leftSpan = ref(0)
const rightSpan = ref(24)
const meta = ref({})
const fieldList = ref([])
const selectForm = async () => {
  let res = await metaApi.selectForm(metaId)
  meta.value = res
  let f = JSON.parse(res.tableForm)
  console.log(f)
  formJson.value.widgetList = f.widgetList
  formJson.value.formConfig = f.formConfig
  console.log(res)
  res.fieldList.forEach((item) => {
    if (item.navigational) {
      rightSpan.value = 18
      leftSpan.value = 6
      navigationals.value.push(item)
    }
    fieldList.value.push({
      key: item.id,
      label: item.fieldDesc
    })
  })
}

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  metaId: metaId,
  dataId: id,
  createTime: []
  // num: ''
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

//进入资源列表
const impResource = (row) => {
  router.push({
    path: '/resource/meta/file',
    query: { metaId: metaId, id: id, versionId: row.id }
  })
}

const isResource = ref(true)

/** 查询版本列表 */
const getList = async () => {
  loading.value = true
  if (metaId === '48' || metaId === '51') {
    isResource.value = false
  }
  try {
    const data = await metaApi.metaVersionList(queryParams)
    list.value = data.list
    list.value.forEach((item) => {
      let itemData = JSON.parse(item.data)
      item.dataName = itemData.title ? itemData.title : itemData.name
      item.metaName = metaName
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 返回按钮操作 */
const retreat = () => {
  router.go(-1)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    let ids = []
    ids.push(id)
    await metaApi.metaVersionDelete(ids)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getList()
  selectForm()
})
</script>
<style scoped lang="scss">
.dialog-footer {
  text-align: center;
}
</style>
